/**
 * Created by yongqiang.ren on 16/9/4.
 */
import {
  mutationWithClientMutationId,
  cursorForObjectInConnection,
} from 'graphql-relay';

import {
  GraphQLID,
  GraphQLString,
  GraphQLNonNull,
  GraphQLFloat,
} from 'graphql';

import { Company } from '../../models';
import { connectionFromType } from '../../connection';
import CompanyType from '../../types/CompanyType';
import UserType from '../../types/UserType';

const AddCompanyMutation = mutationWithClientMutationId({
  name: 'addCompany',
  inputFields: {
    name: { type: new GraphQLNonNull(GraphQLString) },
    email: { type: GraphQLString },
    phone: { type: GraphQLString },
    city: { type: GraphQLString },
    address: { type: GraphQLString },
    note: { type: GraphQLString },
  },
  outputFields: {
    companyEdge: {
      type: connectionFromType('company', CompanyType).edge,
      resolve: async ({ companyId }) => {
        const companies = await Company.findAll();
        const company = companies.find(o => o.get('id') === companyId);
        return {
          cursor: cursorForObjectInConnection(companies, company),
          node: company,
        };
      },
    },
    viewer: {
      type: UserType,
      resolve: async ({ viewer }) => viewer,
    }

  },
  mutateAndGetPayload: async ({ name, email, phone, city, address, note }, { viewer }) => {
    const company = await Company.create({
      name,
      email,
      phone,
      city,
      address,
      note,
    });
    const companyId = company.dataValues.id;
    return { companyId, viewer };
  },
});

export default AddCompanyMutation;
